package com.aliyun.oss.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

@Configuration
@EnableCaching
public class RedisConfiguration {
    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory){
        RedisTemplate redisTemplate = new RedisTemplate();
//        设置链接工厂
        redisTemplate.setConnectionFactory(redisConnectionFactory);
//        这是一个全局的配置，开启事务
        redisTemplate.setEnableTransactionSupport(true);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        // 3. 配置 JSON 序列化器（核心新增）
        ObjectMapper objectMapper = new ObjectMapper();
        // 3.1 允许访问类的所有字段（包括 private）
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 3.2 解决 LocalDateTime/LocalDate 等时间类型序列化问题
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        objectMapper.registerModule(new JavaTimeModule());
        Jackson2JsonRedisSerializer<Object> jsonSerializer = new Jackson2JsonRedisSerializer<>(objectMapper,Object.class);
        // 3. 保留原有序列化器配置
        redisTemplate.setKeySerializer(new StringRedisSerializer());          // key 用 String 序列化
        redisTemplate.setValueSerializer(jsonSerializer);                    // value 用 JSON 序列化
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());     // hashKey 用 String 序列化
        redisTemplate.setHashValueSerializer(jsonSerializer);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

    @Bean
    public RedisCacheManager redisCacheManager(RedisConnectionFactory connectionFactory){
        RedisCacheConfiguration redisCacheConfiguration=RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofMinutes(30))
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())) // key 序列化
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(getJackson2JsonRedisSerializer())) // value 序列化（用 Jackson）
                .disableCachingNullValues(); // 不缓存 null 值
        return RedisCacheManager.builder(connectionFactory)
                .cacheDefaults(redisCacheConfiguration) // 默认配置
                .build();
    }

    // 抽取 Jackson 序列化器配置（复用，避免代码重复）
    private GenericJackson2JsonRedisSerializer getJackson2JsonRedisSerializer() {

        ObjectMapper objectMapper = new ObjectMapper();
        // 允许访问所有字段（包括 private）
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 解决 LocalDateTime/LocalDate 等 Java8 时间类型序列化问题
        // 2. 关键：开启类型信息保留（添加 @class 字段）
        objectMapper.activateDefaultTyping(
                LaissezFaireSubTypeValidator.instance, // 类型验证器（Spring 6+ 推荐）
                ObjectMapper.DefaultTyping.NON_FINAL,   // 对非 final 类保留类型信息（ResultVO 通常是非 final）
                JsonTypeInfo.As.PROPERTY                // 类型信息以属性（@class）形式嵌入 JSON
        );
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        objectMapper.registerModule(new JavaTimeModule()); // 注册 Java8 时间模块
        return new GenericJackson2JsonRedisSerializer(objectMapper);
    }
}
